<template>
	<view class="edit-container page-container">
		<!-- 表单内容 -->
		<view class="form-content">
			<!-- 分类图片 -->
			<!-- <view class="form-section">
				<view class="section-title">分类图标</view>
				<u-upload :fileList="fileList" @afterRead="afterRead" @delete="deleteFile" name="1" multiple
					:maxCount="1" :previewImage="true" width="100" height="100">
				</u-upload>
			</view> -->
			<view class="form-section">
				<view class="section-title">分类图标 <text class="required">*</text></view>
				<view class="upload-area2" @click="uploadIcon">
					<image v-if="formData.group_icon" :src="$tools.buildUrl(formData.group_icon)" class="upload-image2"
						mode="aspectFit" />
					<view v-else class="upload-placeholder">
						<text class="upload-icon">📷</text>
						<text class="upload-text">点击上传</text>
					</view>
				</view>
			</view>

			<!-- 分类名称 -->
			<view class="form-section">
				<view class="section-title">分类名称 <text class="required">*</text></view>
				<u-input v-model="formData.group_name" placeholder="请输入分类名称" maxlength="20" show-word-limit />
			</view>

			<!-- 分类描述 -->
			<!-- <view class="form-section">
				<view class="section-title">分类描述</view>
				<u-input v-model="formData.description" placeholder="请输入分类描述" maxlength="20" show-word-limit />
			</view> -->

			<!-- 排序权重 -->
			<view class="form-section">
				<view class="section-title">分类排序 <text class="required">*</text></view>
				<u-input v-model="formData.group_sort" type="number" placeholder="升序排序" />
			</view>

			<!-- 状态 -->
			<view class="form-section">
				<view class="section-title">分类状态 <text class="required">*</text></view>
				<view class="status-options">
					<view class="status-option" :class="{ active: formData.group_status === 1 }"
						@click="formData.group_status = 1">
						<text class="option-text">启用</text>
					</view>
					<view class="status-option" :class="{ active: formData.group_status === 0 }"
						@click="formData.group_status = 0">
						<text class="option-text">禁用</text>
					</view>
				</view>
			</view>

			<!-- 首页模式：1-轮播 2-横幅 3-双列 4-单列 -->
			<view class="form-section">
				<view class="section-title">首页模式 <text class="required">*</text></view>
				<view class="status-options">
					<view class="status-option" :class="{ active: formData.show_type === 1 }"
						@click="formData.show_type = 1">
						<text class="option-text">轮播</text>
					</view>
					<view class="status-option" :class="{ active: formData.show_type === 2 }"
						@click="formData.show_type = 2">
						<text class="option-text">横幅</text>
					</view>
					<view class="status-option" :class="{ active: formData.show_type === 3 }"
						@click="formData.show_type = 3">
						<text class="option-text">双列</text>
					</view>
					<view class="status-option" :class="{ active: formData.show_type === 4 }"
						@click="formData.show_type = 4">
						<text class="option-text">单列</text>
					</view>
				</view>
			</view>

			<view v-if="formData.show_type>1" class="form-section">
				<text class="section-title">
					<text class="label-text">背景图片</text>
					<text v-if="formData.show_type>1" class="required">*</text>
					<text class="label-text" style="margin-left: 15px;"
						@click="previewMainImage(formData.back_ground_image)">预览</text>
				</text>

				<view class="upload-section">
					<view class="upload-item">
						<view class="upload-area" @click="uploadGroundImage">
							<image v-if="formData.back_ground_image" :src="$tools.buildUrl(formData.back_ground_image)"
								class="upload-image" mode="aspectFill" />
							<view v-else class="upload-placeholder">
								<text class="upload-icon">📷</text>
								<text class="upload-text">点击上传</text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 底部操作按钮 -->
		<view class="bottom-actions fixed-bottom-safe">
			<button class="cancel-btn" @click="goBack">取消</button>
			<button class="save-btn" @click="saveCategory">{{ isEdit ? '保存' : '添加' }}</button>
		</view>
	</view>
</template>

<script>
	import projectConfig from '@/common/config.js';
	export default {
		data() {
			return {
				isEdit: false,
				categoryId: null,
				formData: {
					group_name: '',
					group_icon: '',
					back_ground_image: '',
					group_sort: 0,
					show_type: 1,
					group_type: 1,
					group_status: 1
				},
				fileList: []
			}
		},
		onLoad(options) {
			if (options.id) {
				this.isEdit = true
				this.categoryId = options.id
				this.loadCategoryData()
			}
		},
		methods: {
			// 加载分类数据
			loadCategoryData() {
				this.$api.agent.GetProductGroupInfo({
					id: this.categoryId
				}).then(res => {
					this.formData = res.data
				})
			},

			// 上传图标
			uploadIcon() {
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['camera', 'album'],
					success: (res) => {
						this.uploadPhoto('group_icon', res.tempFilePaths[0]);
					}
				})
			},

			// 上传背景图
			uploadGroundImage() {
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['camera', 'album'],
					success: (res) => {
						this.uploadPhoto('back_ground_image', res.tempFilePaths[0]);
					}
				})
			},

			// 上传图片到服务器
			uploadPhoto(propertyName, tempFilePath) {
				uni.showLoading({
					title: '正在上传'
				})
				const uploadUrl = '/api/App_Upload/UploadFile';
				const headerConfig = this.$sign.buildHeaderSign(uploadUrl, this.userInfo, {}, 'POST'); // 生成签名
				//上传到服务器
				uni.uploadFile({
					url: projectConfig.baseUrl + uploadUrl,
					filePath: tempFilePath, //要上传文件资源的路径 (本地路径)
					name: 'photo', //文件对应的 key，开发者在服务端可以通过这个 key 获取文件的二进制内容
					header: headerConfig,
					formData: {}, //HTTP 请求中其他额外的 form data       
					success: res => {
						uni.hideLoading()
						var jsonObj = this.$tools.parseJsonObject(res.data)
						if (jsonObj.code == 100) {
							//保存成功 
							this.formData[propertyName] = jsonObj.data.relativeUrl
						} else {
							//保存失败
							uni.showToast({
								title: jsonObj.msg,
								icon: 'error'
							})
						}
					},
					fail: err => {
						uni.hideLoading()
						uni.showToast({
							title: '上传图片错误：' + JSON.stringify(err),
							icon: 'error'
						})
					}
				})
			},

			// 预览图片
			previewMainImage(url) {
				uni.previewImage({
					urls: [this.$tools.buildUrl(url)], // 图片地址数组，即使只有一张也要用数组
					current: 0 // 当前显示图片的索引
				});
			},

			// uView上传组件 - 选择图片后的回调
			afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListTmp = this.fileList
				lists.map((item) => {
					fileListTmp.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				this.fileList = fileListTmp
				this.uploadFileToServer()
			},

			// uView上传组件 - 删除图片
			deleteFile(event) {
				this.fileList.splice(event.index, 1)
				this.formData.image = ''
			},

			// 上传到服务器
			uploadFileToServer() {
				setTimeout(() => {
					let fileListTmp = this.fileList
					fileListTmp.map((item) => {
						if (item.status === 'uploading') {
							item.status = 'success'
							item.message = ''
							item.url = item.url || item.thumb
							// 保存图片URL到表单数据
							this.formData.image = item.url
						}
					})
					this.fileList = fileListTmp
				}, 1000)
			},

			// 保存分类
			saveCategory() {
				// 表单验证
				if (!this.formData.group_name.trim()) {
					uni.showToast({
						title: '请输入分类名称',
						icon: 'none'
					})
					return
				}

				if (this.formData.group_name.trim().length > 20) {
					uni.showToast({
						title: '分类名称不能超过20个字符',
						icon: 'none'
					})
					return
				}

				if (!this.formData.group_icon.trim()) {
					uni.showToast({
						title: '请上传分类图标',
						icon: 'none'
					})
					return
				}

				if (this.formData.show_type > 1 && !this.formData.back_ground_image.trim()) {
					uni.showToast({
						title: '请上传背景图片',
						icon: 'none'
					})
					return
				}

				// 处理排序权重
				this.formData.group_sort = Number(this.formData.group_sort) || 0

				// 保存到后端
				uni.showLoading({
					title: this.isEdit ? '保存中...' : '添加中...'
				})

				// 保存信息
				this.$api.agent.SaveProductGroup(this.formData).then(res => {
					uni.hideLoading()
					uni.showToast({
						title: res.msg,
						icon: 'success'
					})
					const pages = getCurrentPages()
					const prevPage = pages[pages.length - 2]
					if (prevPage) {
						prevPage.$vm.onSearch()
					}
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
				})
			},

			// 返回
			goBack() {
				uni.navigateBack()
			}
		}
	}
</script>

<style lang="scss" scoped>
	.edit-container {
		background-color: #f8f9fa;
		min-height: 100vh;
		padding-bottom: calc(140rpx + env(safe-area-inset-bottom));
	}

	.form-content {
		padding: 30rpx;
	}

	.form-section {
		background-color: white;
		border-radius: 20rpx;
		padding: 20rpx 30rpx;
		margin-bottom: 14rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
		border: 1rpx solid #f0f0f0;
	}

	.section-title {
		font-size: 30rpx;
		font-weight: 600;
		color: #2c3e50;
		margin-bottom: 24rpx;
		display: flex;
		align-items: center;
	}

	.section-title::before {
		content: '';
		width: 6rpx;
		height: 32rpx;
		background: linear-gradient(135deg, #52a58a 0%, #6bb6a3 100%);
		border-radius: 3rpx;
		margin-right: 16rpx;
	}

	.required {
		color: #ff4757;
	}

	/* 状态选择 */
	.status-options {
		display: flex;
		gap: 24rpx;
		margin-bottom: 16rpx;
	}

	.status-option {
		flex: 1;
		padding: 10rpx 24rpx;
		background-color: #fafbfc;
		border: 2rpx solid #e8ecf0;
		border-radius: 16rpx;
		text-align: center;
		transition: all 0.3s ease;
		position: relative;
		overflow: hidden;
	}

	.status-option::before {
		content: '';
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: linear-gradient(135deg, #52a58a 0%, #6bb6a3 100%);
		opacity: 0;
		transition: opacity 0.3s ease;
	}

	.status-option.active {
		background-color: #fff;
		border-color: #52a58a;
		box-shadow: 0 4rpx 20rpx rgba(82, 165, 138, 0.15);
	}

	.status-option.active::before {
		opacity: 0.1;
	}

	.option-text {
		font-size: 28rpx;
		color: #7f8c8d;
		position: relative;
		z-index: 1;
		transition: all 0.3s ease;
	}

	.status-option.active .option-text {
		color: #52a58a;
		font-weight: 600;
	}

	/* 图片上传 */
	/* uView上传组件自定义样式 */
	.upload-slot {
		width: 240rpx;
		height: 240rpx;
		border: 3rpx dashed #d0d7de;
		border-radius: 20rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		background: linear-gradient(135deg, #fafbfc 0%, #f6f8fa 100%);
		transition: all 0.3s ease;
		position: relative;
		overflow: hidden;
	}

	.upload-slot::before {
		content: '';
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: linear-gradient(135deg, #52a58a 0%, #6bb6a3 100%);
		opacity: 0;
		transition: opacity 0.3s ease;
	}

	.upload-slot:active {
		border-color: #52a58a;
		transform: scale(0.98);
	}

	.upload-slot:active::before {
		opacity: 0.05;
	}

	.upload-text {
		font-size: 26rpx;
		color: #7f8c8d;
		margin-top: 12rpx;
		margin-bottom: 8rpx;
		font-weight: 500;
		position: relative;
		z-index: 1;
	}

	.upload-tip {
		font-size: 22rpx;
		color: #95a5a6;
		position: relative;
		z-index: 1;
	}



	/* 底部操作按钮 */
	.bottom-actions {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #ffffff;
		border-top: 1rpx solid #f0f0f0;
		padding: 30rpx;
		padding-bottom: calc(30rpx + env(safe-area-inset-bottom));
		display: flex;
		gap: 20rpx;
		z-index: 100;
		box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.1);
	}

	.cancel-btn,
	.save-btn {
		flex: 1;
		border-radius: 48rpx;
		font-size: 32rpx;
		font-weight: 600;
		border: none;
		display: flex;
		align-items: center;
		justify-content: center;
		transition: all 0.3s ease;
		position: relative;
		overflow: hidden;
	}

	.cancel-btn {
		background-color: #f8f9fa;
		color: #7f8c8d;
		border: 2rpx solid #e8ecf0;
	}

	.cancel-btn:active {
		background-color: #e9ecef;
		transform: scale(0.98);
	}

	.save-btn {
		background: linear-gradient(135deg, #52a58a 0%, #6bb6a3 100%);
		color: white;
		box-shadow: 0 8rpx 24rpx rgba(82, 165, 138, 0.3);
	}

	.save-btn::before {
		content: '';
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: linear-gradient(135deg, rgba(255, 255, 255, 0.2) 0%, rgba(255, 255, 255, 0.1) 100%);
		opacity: 0;
		transition: opacity 0.3s ease;
	}

	.save-btn:active {
		transform: translateY(2rpx) scale(0.98);
		box-shadow: 0 4rpx 16rpx rgba(82, 165, 138, 0.4);
	}

	.save-btn:active::before {
		opacity: 1;
	}

	/* 上传区域 */
	.upload-section {
		display: flex;
		gap: 30rpx;
	}

	.upload-item {
		flex: 1;
	}

	.upload-label {
		font-size: 26rpx;
		color: #666;
		margin-bottom: 16rpx;
		display: block;
	}

	.upload-area {
		width: 100%;
		height: 400rpx;
		border: 2rpx dashed #ddd;
		border-radius: 12rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		overflow: hidden;
	}

	.upload-image {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.upload-area2 {
		width: 120rpx;
		height: 120rpx;
		border: 2rpx dashed #ddd;
		border-radius: 12rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		overflow: hidden;
	}

	.upload-image2 {
		width: 100rpx;
		height: 100rpx;
		object-fit: cover;
	}

	.upload-placeholder {
		display: flex;
		flex-direction: column;
		align-items: center;
		color: #999;
	}

	.upload-icon {
		font-size: 48rpx;
		margin-bottom: 10rpx;
	}

	.upload-text {
		font-size: 24rpx;
	}
</style>